<?php

namespace App\Http\Controllers\Api\Main;

use App\Http\Controllers\ApiController;
use App\Http\Resources\User;
use App\Models\Banner;
use App\Models\Category;
use App\Models\Goods;
use App\Models\Template;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;


class MainController extends ApiController
{

    public $expire = 3600;
    
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 首页轮播图
     * @return array
     */
    public function banner()
    {
        $lists = Banner::orderBy('sort','desc')->get();
        return User::collection($lists);
    }

    /**
     * 获取顶级分类
     * @return
     */
    public function getTopCate()
    {
        $lists = self::getApiData('getTopCate');
        if(!$lists){
            $lists = Category::query()->where('pid',0)->orderBy('sort','desc')->get()->toArray();
            Redis::setEx('api:getTopCate',$this->expire,json_encode($lists));

        }else{
            $lists = json_decode($lists,true);
        }
            return self::response($lists,self::SUC_CODE);
    }

    /**
     * 获取全部顶级分类对应的二级分类
     */
    public function getCates()
    {
        $cates = self::getApiData('getCates');
        if(!$cates){
            $lists = DB::table('goods_cate as g')
                ->leftjoin('goods_cate as c','g.id','=','c.pid')
                ->where('g.pid',0)
                ->select('g.id as gid','g.pid as gpid','g.cate_name as gcate_name','g.cate_img as gcate_img','c.id as cid','c.pid as cpid','c.cate_name as ccate_name','c.cate_img as ccate_img')
                ->orderBy('g.sort','desc')
                ->orderBy('c.sort','desc')
                ->get();
            $cates = array();
            foreach ($lists as $k=>$v){
                $temp =array();
                $temp['id'] = $v->cid;
                $temp['pid'] = $v->cpid;
                $temp['cate_name'] = $v->ccate_name;
                $temp['cate_img'] = $v->ccate_img;
                $cates[$v->gid]['id'] = $v->gid;
                $cates[$v->gid]['pid'] = $v->gpid;
                $cates[$v->gid]['cate_name'] = $v->gcate_name;
                $cates[$v->gid]['cate_img'] = $v->gcate_img;
                $cates[$v->gid]['item'][] = $temp;
            }
            Redis::setEx('api:getCates',$this->expire,json_encode($cates));
        }else{
            $cates = json_decode($cates,true);
        }

        return self::response($cates,self::SUC_CODE);
    }

    /**
     * 获取首页热销商品
     */
    public function getHotGoods()
    {
        $lists = self::getApiData('getHotGoods');
        if(!$lists){
        $lists = DB::table('order_goods')
            ->select(DB::raw('count(goods_number) as num,sku_id as product_id,goods_id'))
            ->groupBy('sku_id')
            ->orderBy('num','desc')
            ->get();
        //如果热销商品不足4件则使用排序前四的商品
        if($lists->count()<4){
            $lists = DB::table('products')->select('product_id','goods_id')->where('disabled','=',0)->orderBy('p_order','desc')->get();
        }
        $product_arr = [];
        $count = 0;
        foreach ($lists as $key => $val){
            if($count<4){
                $product_arr[] = $val->product_id;
            }
            $count++;
        }

        $goods = DB::table('products')
            ->join('goods','products.goods_id','=','goods.goods_id')
            ->select('products.*')
            ->selectRaw(DB::raw('CONCAT("'.config('app.url').'",image) AS image')->getValue())
            ->whereIn('products.product_id',$product_arr)
            ->get()
            ->where('goods.disabled','=',0)
            ->toArray();
//            Redis::setEx('api:getHotGoods',$this->expire,json_encode($goods));
        }else{
            $goods = json_decode($lists,true);
        }
        return self::response($goods,self::SUC_CODE);

    }

    /**
     * 获取产品列表
     */
    public function getGoods(Request $request)
    {
        $cate_id = $request->get('cate_id','');
        if(empty($cate_id)){
            $cate_id = 0;
        }
        $lists = self::getApiData('getGoods:'.$cate_id);
        if(!$lists){
            $lists = Template::api_front_list();
            if(!empty($lists)){
                Redis::setEx('api:getGoods:'.$cate_id,$this->expire,json_encode($lists));
            }
        }else{
            $lists = json_decode($lists,true);
        }
        return self::response($lists,self::SUC_CODE);
    }



    public function getPreferGoods()
    {
           $goods_id_max    = Goods::count();
           $goods_id[0]     = mt_rand(1,$goods_id_max);

           if ($goods_id[0]+1<=$goods_id_max){
               $goods_id[1]    =  $goods_id[0]+1;
           }else if ($goods_id[0]-1>=0){
               $goods_id[1]    =  $goods_id[0]-1;
           }else{
               $goods_id[1]    = mt_rand(1,$goods_id_max);
           }
            $lists = DB::table('goods')->select('*')
                ->where('marketable','=',1)
                ->whereIn('goods_id',$goods_id)
                ->selectRaw(DB::raw('CONCAT("'.config('app.url').'",image) AS image'))
                ->get();


        return self::response($lists,self::SUC_CODE);
    }





    /**
     * 搜索产品
     * @param title 搜索标题
     */
    public function serachGoods(Request $request)
    {
        $title = htmlspecialchars($request->title);
        $lists = DB::table('goods')->orderBy('sort','desc')->select('*')->selectRaw(DB::raw('CONCAT("'.config('app.url').'",image) AS image')->getValue())->where([['marketable',1],['disabled',0]])->where('goods_name','like',"%$title%")->get();
        if($lists->count()>0){
            return self::response($lists,self::SUC_CODE);
        }else{
            return self::response([],self::SUC_CODE,"未搜索到{$title}相关商品");
        }
    }

    /**  以下商品详情页接口汇总   **/

    /**
     *商品详情页-->商品表中的基本信息
     * @param goods_id int
     */
    public function getBaseGoodsMessage(Request $request,Goods $goodsModel)
    {
        /* 设计以goods_id 为标识的redis缓存变量*/
        $goods_id = intval($request->goods_id,0);
        if(!$goods_id){
            return self::response([],self::SUC_CODE,"参数错误");
        }
        $list = [];
        if(!$list){
            $list = $goodsModel->api_get_goods_detail($goods_id);
//            Redis::setEx('api:getBaseGoodsMessage:'.$goods_id,$this->expire,json_encode($list));
        }else{
            $list = json_decode($list,true);
        }
        return self::response($list,self::SUC_CODE);
    }

    /**20180801 0:54修改 修改返回格式
     * @param $id
     * 获取产品规格
     */
    public function getGoodFormat(Request $request,Goods $goodsModel)
    {
        $id = $request->input('goods_id');
        $formats = self::getApiData('getGoodFormat:'.$id);
        $formats = [];
        if(!$formats){
            //查询出相关spu_id商品
            $formats = $goodsModel->api_get_props($id);
            Redis::setEx('api:getGoodFormat:'.$id,$this->expire,json_encode($formats));
        }else{
            $formats = json_decode($formats,true);
        }
        return self::response($formats,self::SUC_CODE);
    }

    /**
     * @param $id
     * 获取商品对应的评论
     */
    public function getGoodComment(Request $request)
    {
        $id = $request -> get('goods_id');
        if(empty($id)){
            return self::response(null,self::ERROR_CODE,'商品id不能为空');
        }
//        $comment = self::getApiData('getGoodComment:'.$id);
        $comment = [];
        if(!$comment){
            /*查询出评论及其产品规格*/
            $mess = DB::table('user_comments as comment')
                ->join('user as u','u.id','=','comment.uid')
                ->join('sku_props_vals as sku','sku.sku_id','=','comment.sku_id')
                ->join('props as pro','pro.props_id','=','sku.props_id')
                ->join('props_vals as val','val.props_val_id','=','sku.props_val_id')
                ->select('comment.*','pro.name as p_name','val.name as v_name','u.user_name as username')
                ->where('comment.goods_id','=',$id)
                ->get()
                ->map(function($value){
                    return (array) $value;
                })
                ->toArray();
            $comment = array();
            foreach ($mess as $k=>$v)
            {
                $comment[$v['id']]['id'] = $v['id'];
                $comment[$v['id']]['username'] = $v['username'];
                $comment[$v['id']]['comment'] = $v['comment'];
                $comment[$v['id']]['avatar'] = $v['avatar'];
                $comment[$v['id']]['created_at'] = $v['created_at'];
                $comment[$v['id']]['format'] .= "{$v['p_name']}:{$v['v_name']}";
            }
            $comment = array_values($comment);
            if(!empty($comment)){
                Redis::setEx('api:getGoodComment:'.$id,$this->expire,json_encode($comment));
            }
        }else{
            $comment = json_decode($comment,true);
        }
        return self::response($comment,self::SUC_CODE);
    }

    public function getCoupon()
    {
        $coupon = self::getApiData('getCoupon');

    }

    /**商品详情-选择属性和属性值 返回sku具体信息
     * @param Request $request
     * @param Goods $goodsModel
     */
    public function getSkuByPropsAndVal(Request $request,Goods $goodsModel)
    {
        $props_val_arr = $request->input('props_val_arr');
        if(empty($props_val_arr) || empty($props_val_arr[0])){
            return self::response(null,self::ERROR_CODE,'请选择商品属性!');
        }
        //如果传过来的不是数组，则可以认为是goods_id
        if(is_numeric($props_val_arr)){
            $sku = $goodsModel->api_get_sku_info($props_val_arr);
            return self::response($sku);
        }
        $keys_arr = array_keys($props_val_arr[0]);
        if(count(array_intersect($keys_arr,['goods_id','props_val_id','props_id']))!==3){
            return self::response(null,self::ERROR_CODE,'请确保你的参数值是否正确!');
        }
        $sku = $goodsModel->api_get_sku_info($props_val_arr);
        return self::response($sku);
    }

    #获取我的评论
    public function getMyComment(Request $request)
    {
        $uid = intval($request->uid);
        if(!$uid){
            return self::response(null,self::ERROR_CODE,'提供有效uid');
        }
        $list = DB::table('user_comments as users')
                ->join('products','users.sku_id','=','products.product_id')
                ->join('goods','products.goods_id','=','goods.goods_id')
                ->join('user','user.id','=','users.uid')
                ->select('users.*','products.*','user.user_name')
                ->selectRaw(DB::raw('CONCAT("'.config('app.url').'",image) AS image')->getValue())
                ->where('users.uid','=',$uid)
                ->orderBy('id','desc')
                ->get()
                ->toArray();
        if(!$list){
            return self::response(null,self::SUC_CODE,'暂无评论');
        }
        return self::response($list,self::SUC_CODE);
    }
}
